local locale = GetLocale()
local L = setmetatable(locale == "zhCN" and {
	["(.*) won: (.+)"] = "(.*)赢得了：(.+)",
	["%s|Hgreedbeacon:%d|h[%s roll]|h|r %s won %s "] = "%s|Hgreedbeacon:%d|h[%s]|h|r %s 赢得了 %s ",
	["(.*) has?v?e? selected (.+) for: (.+)"] = "(.+)选择了(.+)取向：(.+)",
	["(.+) Roll . (%d+) for (.+) by (.+)"] = "（(.+)）(%d+)点：(.+)（(.+)）",
	[" passed on: "] = "放弃了：",
	[" automatically passed on: "] = "自动放弃了",
	["You passed on: "] = "你放弃了：",
	["Everyone passed on: "] = "所有人都放弃了：",
	["Greed"] = GREED,
	["Need"] = NEED,

	["Winner:"] = "赢家:",
	[" roll|r - "] = "|r - ",
	["ERROR: No match found for"] = "错误: 没有此物品的掷点信息: ",
} or locale == "zhTW" and {
	["(.*) won: (.+)"] = "(.*)贏得了:(.+)",
	["%s|Hgreedbeacon:%d|h[%s roll]|h|r %s won %s "] = "%s|Hgreedbeacon:%d|h[%s]|h|r %s 贏得了 %s ",
	["(.*) has?v?e? selected (.+) for: (.+)"] = "(.+)選擇了(.+)優先:(.+)",
	["(.+) Roll . (%d+) for (.+) by (.+)"] = "(.+) - (.+)由(.+)擲出(%d+)",
	[" passed on: "] = "放棄了:",
	[" automatically passed on: "] = "自動放棄:",
	["You passed on: "] = "你放棄了:",
	["Everyone passed on: "] = "所有人都放棄了:",
	["Greed"] = "貪婪 -",
	["Need"] = "需求 -",

	["Winner:"] = "贏家:",
	[" roll|r - "] = "|r - ",
	["ERROR: No match found for"] = "錯誤: 沒有此物品的擲點信息: ",
} or {}, {__index = function(t,i) return i end})

local colorneed, colorgreed = "|cffff0000", "|cffffff00"
local coloredwords = {[L.Greed] = colorgreed..L.Greed, [L.Need] = colorneed..L.Need}
local rolls, db = {}

local function Print(...) print("|cFF33FF99GreedBeacon|r:", ...) end

local debugf = tekDebug and tekDebug:GetFrame("GreedBeacon")
local function Debug(...) if debugf then debugf:AddMessage(string.join(", ", ...)) end end


local function FindRoll(link, player, hasselected)
	for i,roll in ipairs(rolls) do
		if roll._link == link and not roll._winner and (not roll[player] or hasselected) then return roll end
	end
	Debug("New roll started", link)
	local newroll = {_link = link}
	table.insert(rolls, newroll)
	return newroll
end


local f = CreateFrame("Frame")
f:RegisterEvent("ADDON_LOADED")
f:SetScript("OnEvent", function(self, event, addon)
	if addon:lower() ~= "greedbeacon" then return end

	GreedBeaconDB = GreedBeaconDB or {}
	db = GreedBeaconDB
		db.frame = "ChatFrame3"
		for i=7,1,-1 do
			local name = "ChatFrame"..i
			for i,v in pairs(_G[name].messageTypeList) do if v == "LOOT" then db.frame = name end end
		end
		Debug("Initializing DB to", db.frame)

	f:UnregisterEvent("ADDON_LOADED")
	f:RegisterEvent("CHAT_MSG_LOOT")
	f:SetScript("OnEvent", function(self, event, msg)
		local rolltype, rollval, link, player
		if locale == "zhTW" then
			rolltype, link, player, rollval = msg:match(L["(.+) Roll . (%d+) for (.+) by (.+)"])
		else
			rolltype, rollval, link, player = msg:match(L["(.+) Roll . (%d+) for (.+) by (.+)"])
		end
		if player then
			local roll = FindRoll(link, player, true)
			Debug("Roll detected", player, rolltype, rollval, link)
			roll[player] = (rolltype == L.Need and colorneed or colorgreed)..rollval
			roll._type = rolltype
			return
		end

		local player, selection, link = msg:match(L["(.*) has?v?e? selected (.+) for: (.+)"])
		if player and player ~= "" then
			player = player == YOU and UnitName("player") or player
			Debug("Selection detected", player, selection, link)
			FindRoll(link, player)[player] = coloredwords[selection]
			return
		end

		local player, link = msg:match(L["(.*) won: (.+)"])
		if player then
			player = player == YOU and UnitName("player") or player
			for i,roll in ipairs(rolls) do
				if roll._link == link and roll[player] and not roll._printed then
					roll._printed = true
					roll._winner = player
					Debug("Roll completed", roll._type or "nil", i, player, link)
					local msg = string.format(L["%s|Hgreedbeacon:%d|h[%s roll]|h|r %s won %s "], roll._type == L.Need and colorneed or colorgreed, i, roll._type or "???", player, link)
					_G[db.frame]:AddMessage(msg)
					return
				end
			end
			Print(L["ERROR: No match found for"], msg)
			return
		end
	end)
end)


ChatFrame_AddMessageEventFilter("CHAT_MSG_LOOT", function(self, event, msg)
	if msg:match(L["(.*) won: (.+)"]) or msg:match(L["(.*) has?v?e? selected (.+) for: (.+)"]) or msg:match(L["(.+) Roll . (%d+) for (.+) by (.+)"])
		or msg:match(L["You passed on: "]) or msg:match(L[" automatically passed on: "]) or (msg:match(L[" passed on: "]) and not msg:match(L["Everyone passed on: "])) then
		Debug("Supressing chat message", msg)
		return true
	end
end)


local orig2 = SetItemRef
function SetItemRef(link, text, button)
	local id = link:match("greedbeacon:(%d+)")
	if id then
		ShowUIPanel(ItemRefTooltip)
		if not ItemRefTooltip:IsShown() then ItemRefTooltip:SetOwner(UIParent, "ANCHOR_PRESERVE") end

		local i = tonumber(id)
		local val = rolls[i]
		ItemRefTooltip:ClearLines()
		ItemRefTooltip:AddLine(coloredwords[val._type]..L[" roll|r - "]..val._link)
		ItemRefTooltip:AddDoubleLine(L["Winner:"], "|cffffffff"..val._winner)
		for i,v in pairs(val) do if string.sub(i, 1, 1) ~= "_" then ItemRefTooltip:AddDoubleLine(i, v) end end
		ItemRefTooltip:Show()
	else return orig2(link, text, button) end
end
